package com.starsoft.frame.base.job;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.starsoft.frame.base.bean.BaseJob;
import com.starsoft.frame.base.bean.BaseJobLog;
import com.starsoft.frame.base.service.JobLogService;
import com.starsoft.frame.util.DateUtil;
import com.starsoft.frame.util.SpringContext;

public abstract class AbstractJob implements Job {

	private static Logger logger = LoggerFactory.getLogger(AbstractJob.class);

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		long t = System.currentTimeMillis();
		BaseJob job = (BaseJob) context.getJobDetail().getJobDataMap().get("baseJob");
		logger.info("运行任务开始：" + job.getJobName());
		BaseJobLog jobLog = getJobLog(context);
		try {
			run(context, jobLog);
			saveJobLog(jobLog);
		} catch (Exception e) {
			saveJobLog(jobLog, e);
		}
		t = (System.currentTimeMillis() - t) / 1000;
		logger.info("运行任务结束，用时：{}s", t);
	}

	abstract public void run(JobExecutionContext context, BaseJobLog jobLog);

	protected BaseJobLog getJobLog(JobExecutionContext context) {
		BaseJob job = (BaseJob) context.getJobDetail().getJobDataMap().get("baseJob");
		BaseJobLog jobLog = new BaseJobLog();
		jobLog.setStartTime(DateUtil.getTimestamp());
		jobLog.setJobCode(job.getJobCode());
		return jobLog;
	}

	protected void saveJobLog(BaseJobLog jobLog) {
		if (jobLog.getStatus() == null) {
			jobLog.setStatus("Y");
		}
		jobLog.setEndTime(DateUtil.getTimestamp());
		SpringContext.getBean(JobLogService.class).save(jobLog);
	}

	protected void saveJobLog(BaseJobLog jobLog, Exception e) {
		logger.error("{} Job 运行异常", this.getClass().getSimpleName(), e);
		
		jobLog.setStatus("N");
		jobLog.setEndTime(DateUtil.getTimestamp());

		StringWriter runLongSw = new StringWriter();
		PrintWriter runLongPw = new PrintWriter(runLongSw);
		e.printStackTrace(runLongPw);
		jobLog.setDesp(runLongSw.toString());

		SpringContext.getBean(JobLogService.class).save(jobLog);
	}

}
